//
//  DistrictViewController.m
//  MeiTuan
//
//  Created by Ansen on 15-3-9.
//  Copyright (c) 2015年 Ansen. All rights reserved.
//

#import "DistrictViewController.h"
#import "CityViewController.h"
#import "NavController.h"
#import "HomeDropdown.h"
#import "Region.h"
#import "UIView+Extension.h"
#import "Const.h"

@interface DistrictViewController ()<HomeDropdownDataSource,HomeDropdownDelegate>

@end

@implementation DistrictViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 创建下拉菜单
    UIView *title = [self.view.subviews firstObject];
    HomeDropdown *dropdown = [HomeDropdown dropdown];
    dropdown.y = title.height;
    dropdown.dataSource = self;
    dropdown.delegate = self;
    [self.view addSubview:dropdown];
    
    // 设置控制器在popover中的尺寸
    self.preferredContentSize = CGSizeMake(dropdown.width, CGRectGetMaxY(dropdown.frame));;
}

- (IBAction)changeCity {
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    CityViewController *city = [[CityViewController alloc] init];
    NavController *nav = [[NavController alloc] initWithRootViewController:city];
    nav.modalPresentationStyle = UIModalPresentationFormSheet;
    [[UIApplication sharedApplication].keyWindow.rootViewController  presentViewController:nav animated:YES completion:nil];

}

-(NSInteger)numberOfRowsInMainTable:(HomeDropdown *)homeDropdown
{
    return self.regions.count;
}

-(NSString *)homeDropdown:(HomeDropdown *)homeDropdown titleForRowInMainTable:(int)row
{
    Region *region = self.regions[row];
    return region.name;
}

-(NSArray *)homeDropdown:(HomeDropdown *)homeDropdown subDataForRowInMainTable:(int)row
{
    Region *region = self.regions[row];
    return region.subregions;
}

-(void)homeDropdown:(HomeDropdown *)homeDropdown didSelectRowInMainTable:(int)row
{
    Region *region = self.regions[row];
    if (region.subregions.count == 0) {
        [NotificationCenter postNotificationName:RegionDidChangeNotification object:nil userInfo:@{SelectRegionName:region.name}];
    }
}

-(void)homeDropdown:(HomeDropdown *)homeDropdown didSelectRowInSubTable:(int)subRow inMainTable:(int)mainRow
{
    Region *region = self.regions[mainRow];
    [NotificationCenter postNotificationName:RegionDidChangeNotification object:nil userInfo:@{SelectRegionName:region.name,SelectSubregionName:region.subregions[subRow]}];
}


@end
